package com.lyh.hkcloud.module.m1300023;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.*;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.*;
import androidx.annotation.RequiresApi;
import cn.yhq.validate.ValidateManager;
import com.lyh.hkcloud.R;
import com.lyh.hkcloud.activity.HomeActivity;
import com.lyh.hkcloud.adapter.AutoCompleteTextViewAdapter;
import com.lyh.hkcloud.base.BaseActivity;
import com.lyh.hkcloud.constants.BusinessConstants;
import com.lyh.hkcloud.constants.HttpUrlComstants;
import com.lyh.hkcloud.module.common.ActivityUtil;
import com.lyh.hkcloud.module.common.Loading;
import com.lyh.hkcloud.module.m1300023.adapter.ListViewAdapter;
import com.lyh.hkcloud.module.m1300023.service.Service;
import com.lyh.hkcloud.util.base.*;
import com.lyh.hkcloud.util.http.listener.json.JsonFailuredListener;
import com.lyh.hkcloud.util.http.listener.json.JsonSuccessListener;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.*;

/**
 * @author: zhongfan
 * @program: hkCloud
 * @description:借用资产
 * @company—date: 利元数据 2022-02-16 10:04
 **/
public class IndexActivity extends BaseActivity implements View.OnClickListener, ListViewAdapter.DeleteCallback, DatePicker.OnDateChangedListener, TimePicker.OnTimeChangedListener {

    private ImageView goBack;
    private TextView tvDate;
    private EditText etBorrower;
    private Button btReceiver;
    /*private Spinner spLocationNumber;
    private Spinner spCostCenter;*/
    private AutoCompleteTextView atvLocationNumber;
    private AutoCompleteTextView atvCostCenter;
    private EditText etProject;
    private EditText etPurpose;
    private EditText etAssets;
    private Service service;

    private ListView lvAssets;
    private List<Map<String, Object>> dataMap = new ArrayList<>();
    private ListViewAdapter listViewAdapter;
    private Integer receiverFocusEvent = 0;

    /**
     * 提交资产信息
     */
    List<String> assetsDataId = new ArrayList<String>();
    List<String> assetIdList = new ArrayList<>();
    Map<String, Object> assetsMap = new HashMap<>();


    /**
     * 位置编号，成本中心
     */
    List<String> locationArray;
    List<String> costArray;

    private int year, month, day, hour, minute;
    private StringBuffer date, time;

    @Override
    protected Activity getActivity() {
        return this;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_1300023;
    }

    @Override
    protected int getClearResId() {
        return R.id.bt_resetting;
    }

    @Override
    protected int getSubmitResId() {
        return R.id.bt_receiver;
    }


    @Override
    protected void onBeginInit() {
        service = new Service(IndexActivity.this);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void initView() {
        goBack = findViewById(R.id.go_back);
        tvDate = findViewById(R.id.tv_date);
        etBorrower = findViewById(R.id.et_borrower);
        btReceiver = findViewById(R.id.bt_receiver);
        lvAssets = findViewById(R.id.lv_assets);
        /*spLocationNumber = findViewById(R.id.sp_location_number);
        spCostCenter = findViewById(R.id.sp_cost_center);*/
        atvLocationNumber=findViewById(R.id.atv_location_number);
        //atvCostCenter=findViewById(R.id.atv_cost_center);
        etProject = findViewById(R.id.et_project);
        etPurpose = findViewById(R.id.et_purpose);
        etAssets= findViewById(R.id.et_assets);
        //获得焦点，并关闭软盘
        etAssets.setShowSoftInputOnFocus(false);
        tvDate.setOnClickListener(this);
        goBack.setOnClickListener(this);
        etBorrower.setOnClickListener(this);
        getSupportActionBar().hide();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        listViewAdapter = new ListViewAdapter(this, dataMap, IndexActivity.this);
        listViewAdapter.setDeleteCallback(this);
        lvAssets.setAdapter(listViewAdapter);

        date = new StringBuffer();
        time = new StringBuffer();

        initDateTime();
        querySpinner(null, null);
    }

    //时间分发方法重写
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        //如果是点击事件，获取点击的view，并判断是否要收起键盘
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            //获取目前得到焦点的view
            View v = getCurrentFocus();
            //判断是否要收起并进行处理
            if (ActivityUtil.isShouldHideKeyboard(v, ev)) {
                //ActivityUtil.hideKeyboard(v.getWindowToken(), this, etBorrower);
                ActivityUtil.hideKeyboard(v.getWindowToken(), this, etProject);
                ActivityUtil.hideKeyboard(v.getWindowToken(), this, etPurpose);
            }
        }
        //这个是activity的事件分发，一定要有，不然就不会有任何的点击事件了
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void initEvent() {
        etBorrower.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    if (BusinessConstants.SCAN_WHEN_SELECTED.equals(String.valueOf(etBorrower.getText()))) {
                        etBorrower.setText("");
                    }
                    receiverFocusEvent = 1;
                } else {
                    if (etBorrower.getText() == null || "".equals(etBorrower.getText().toString())) {
                        etBorrower.setText(BusinessConstants.SCAN_WHEN_SELECTED);
                    } else {

                        JSONObject jsonObject = new JSONObject();
                        try {

                            jsonObject.put("psncode", etBorrower.getText());

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        //查询人员信息
                        queryPersonnelInformation(jsonObject);
                    }
                    receiverFocusEvent = 0;
                }
            }
        });
        etProject.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    if (BusinessConstants.PROJECT.equals(String.valueOf(etProject.getText()))) {
                        etProject.setText("");
                    }
                    receiverFocusEvent = 1;
                } else {
                    if (etProject.getText() == null || "".equals(etProject.getText().toString())) {
                        etProject.setText(BusinessConstants.PROJECT);
                    }
                    receiverFocusEvent = 0;
                }
            }
        });
        etPurpose.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    if (BusinessConstants.PURPOSE.equals(String.valueOf(etPurpose.getText()))) {
                        etPurpose.setText("");
                    }
                    receiverFocusEvent = 1;
                } else {
                    if (etPurpose.getText() == null || "".equals(etPurpose.getText().toString())) {
                        etPurpose.setText(BusinessConstants.PURPOSE);
                    }
                    receiverFocusEvent = 0;
                }
            }
        });

        etAssets.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    if (BusinessConstants.SCAN_WHEN_ASSETS.equals(String.valueOf(etAssets.getText()))) {
                        etAssets.setText("");
                    }
                    receiverFocusEvent = 1;
                } else {
                    if (etAssets.getText() == null || "".equals(String.valueOf(etAssets.getText()))) {
                        etAssets.setText(BusinessConstants.SCAN_WHEN_ASSETS);
                    }
                    receiverFocusEvent = 0;
                }
            }
        });

        //回车事件，查询资产
        etAssets.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                etBorrower.clearFocus();
                /*查询资产*/
                JSONObject jsonObject = new JSONObject();
                try {
                    String msg=etAssets.getText().toString().replace(BusinessConstants.SCAN_WHEN_ASSETS,"");
                    if (assetIdList.indexOf(msg) != -1) {
                        Toast.makeText(IndexActivity.this, "请不要重复扫描", Toast.LENGTH_SHORT).show();
                    }else if(StringUtils.isNotEmpty(msg)){
                        jsonObject.put("psncode", msg);
                        jsonObject.put("facardcode", msg);
                        queryAssetInformation(jsonObject);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                etAssets.setText("");
                return true;
            }
        });
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        registerReceiver(receiver, Filter());
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        unregisterReceiver(receiver);
    }

    @Override
    protected void onClear(View... ignores) {
        super.onClear(ignores);
       /* spLocationNumber.setSelection(0);
        spCostCenter.setSelection(0);*/
        dataMap.clear();
        assetIdList.clear();
        etAssets.setText("");
        updateAssetList();
        Log.v("clear**", "清空**");
    }

    @Override
    protected void onSubmit() {
        /*参数校验*/
        Editable borrower = etBorrower.getText();
        CharSequence returnDate = tvDate.getText();
        Editable project = etProject.getText();
        Editable purpose = etPurpose.getText();

        if (borrower == null || BusinessConstants.SCAN_WHEN_SELECTED.equals(borrower.toString())) {
            Toast.makeText(IndexActivity.this, "借用人不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (returnDate == null || "".equals(returnDate) || BusinessConstants.SELECT_DATE.equals(returnDate.toString())) {
            Toast.makeText(IndexActivity.this, "归还日期不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        /*if (spLocationNumber.getSelectedItemPosition() == -1  || "".equals(locationArray.get(spLocationNumber.getSelectedItemPosition())) || BusinessConstants.PLEASE_SELECT.equals(locationArray.get(spLocationNumber.getSelectedItemPosition()))) {
            Toast.makeText(IndexActivity.this, "位置编号不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (spCostCenter.getSelectedItemPosition() == -1 || "".equals(costArray.get(spCostCenter.getSelectedItemPosition())) || BusinessConstants.PLEASE_SELECT.equals(costArray.get(spCostCenter.getSelectedItemPosition()))) {
            Toast.makeText(IndexActivity.this, "成本中心不能为空", Toast.LENGTH_SHORT).show();
            return;
        }*/
        if (StringUtils.isEmpty(atvLocationNumber.getText().toString())) {
            Toast.makeText(com.lyh.hkcloud.module.m1300023.IndexActivity.this, "位置编号不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        /*if (StringUtils.isEmpty(atvCostCenter.getText().toString())) {
            Toast.makeText(com.lyh.hkcloud.module.m1300023.IndexActivity.this, "成本中心不能为空", Toast.LENGTH_SHORT).show();
            return;
        }*/
        if(!locationArray.contains(atvLocationNumber.getText().toString())){
            Toast.makeText(com.lyh.hkcloud.module.m1300023.IndexActivity.this, "位置编号不存在", Toast.LENGTH_SHORT).show();
            return;
        }
       /* if(!costArray.contains(atvCostCenter.getText().toString())){
            Toast.makeText(com.lyh.hkcloud.module.m1300023.IndexActivity.this, "成本中心不存在", Toast.LENGTH_SHORT).show();
            return;
        }*/
        if (project == null || "".equals(project) || BusinessConstants.PROJECT.equals(project.toString())) {
            Toast.makeText(IndexActivity.this, "项目不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (purpose == null || "".equals(purpose) || BusinessConstants.PURPOSE.equals(purpose.toString())) {
            Toast.makeText(IndexActivity.this, "用途不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        if (assetIdList.size() == 0) {
            Toast.makeText(IndexActivity.this, "请扫描添加资产", Toast.LENGTH_SHORT).show();
            return;
        }

        if (assetsMap.get("field_6887600017557688328") == null) {
            Toast.makeText(IndexActivity.this, "人员信息为空，", Toast.LENGTH_SHORT).show();
            return;
        }

        btReceiver.setEnabled(false);
        int assetNumber = 0;


        //String locationNumber = locationArray.get(spLocationNumber.getSelectedItemPosition());
        String locationNumber =atvLocationNumber.getText().toString();
        //String costCenter = costArray.get(spCostCenter.getSelectedItemPosition());
        //String cost =atvCostCenter.getText().toString();


        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject();
            List<String> facardidList = new ArrayList<>();
            List<Map<String, Object>> dataList = new ArrayList<>();

            //查询人员信息
//            jsonObject.put("psncode", etBorrower.getText());
//            queryPersonnelInformation(jsonObject);

            //归还日期
            assetsMap.put("field_6899956749994823680", tvDate.getText().toString());
            assetsMap.put("field_6908339300836839424", etProject.getText().toString());
            assetsMap.put("field_6887600017528328199", etPurpose.getText().toString());

            //位置代码、位置名称
            String[] split = locationNumber.split(BusinessConstants.SEPARATOR);
            if (split != null && split.length == 2) {
                assetsMap.put("field_6887600017540911109", split[0]);
                assetsMap.put("field_6887600017549299712", split[1]);
            }

            for (Map<String, Object> val : dataMap) {
                Map<String, Object> stringObjectHashMap = new HashMap<>();
                facardidList.add(val.get("facardid") == null ? "" : val.get("facardid").toString());
                stringObjectHashMap.put("id", val.get("facardid") == null ? "" : val.get("facardid").toString());
                stringObjectHashMap.put("num", val.get("num") == null ? "" : val.get("num").toString());
                dataList.add(stringObjectHashMap);
            }

            List<Object> facardIdList = new ArrayList<>();
            for (Map<String, Object> data : dataMap) {
                if (data.get("facardid") != null && !"".equals(data.get("facardid"))) {
                    facardIdList.add(data.get("facardid"));
                }
            }

            jsonObject.put("dataIds", JsonUtil.toJSONArray(facardIdList));
            jsonObject.put("data", JsonUtil.toJSONArray(dataList));
            jsonObject.put("maindata", JsonUtil.toJSONObject(assetsMap));
            jsonObject.put("userid", SaveData.getString(this, "userid"));
            jsonObject.put("username", SaveData.getString(this, "userName"));

            Log.v("jsonObject资产信息提交", jsonObject.toString());

        } catch (JSONException e) {
            e.printStackTrace();
        }

//        if (assetNumberList.size() == 0 || assetsMap.size() == 0) {
//            Toast.makeText(IndexActivity.this, "请输入信息后提交", Toast.LENGTH_SHORT).show();
//            return;
//        }

        showProgressDialog("提示", "提交中...");

        service.post(jsonObject, HttpUrlComstants.ASSET_BORROWING, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                ToastUtils.makeText(IndexActivity.this, response.optString("message"), ToastUtils.LENGTH_SHORT).show();
                LoadingUtils.getInstance(IndexActivity.this).hide();
//                onClear();
                //返回
                onClick(goBack);
            }
        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error", response.optString("message"));
                LoadingUtils.getInstance(IndexActivity.this).hide();
                btReceiver.setEnabled(true);
            }
        });
        hideProgressDialog();
    }

    private static IntentFilter Filter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BusinessConstants.ACTION);
        return intentFilter;
    }

    private void setATVData(List<String>data,AutoCompleteTextView atc){
        AutoCompleteTextViewAdapter actvAdapter =new AutoCompleteTextViewAdapter(this, R.layout.item_select,data);
        atc.setAdapter(actvAdapter);
        atc.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                AutoCompleteTextView view = (AutoCompleteTextView) v;
                if (hasFocus) {
                    view.showDropDown();
                }
            }
        });
        atc.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                AutoCompleteTextView view = (AutoCompleteTextView) v;
                view.showDropDown();
                return false;
            }
        });
    }

    /**
     * 扫描 接收者
     *
     * @author: zhongfan
     * @Date 2022/2/15 21:00
     **/
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            etBorrower.clearFocus();
            etProject.clearFocus();
            etPurpose.clearFocus();
            String msg = intent.getStringExtra(BusinessConstants.TAG);
            Log.i(BusinessConstants.TAG, msg);

            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("psncode", msg);
                jsonObject.put("facardcode", msg);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            //添加接收人
            if (receiverFocusEvent == 1) {
                etBorrower.setText(msg);
                /*查询人员信息*/
                queryPersonnelInformation(jsonObject);
                return;
            }

            if (assetIdList.indexOf(msg) != -1) {
                Toast.makeText(IndexActivity.this, "请不要重复扫描", Toast.LENGTH_SHORT).show();
                return;
            }

            showProgressDialog("提示", "查询中...");
            /*查询资产*/
            queryAssetInformation(jsonObject);

            hideProgressDialog();
        }
    };

    /**
     * 查询资产
     */
    public void queryAssetInformation(JSONObject jsonObject) {
        service.post(jsonObject, HttpUrlComstants.QUERY_ASSET_DETAILS, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {

                try {
                    JSONObject jsonObject3 = JsonUtil.getJsonObject(response, "facardinfo", IndexActivity.this);
                    if (jsonObject3 == null) {
                        ToastUtils.makeText(IndexActivity.this, "查询信息为空", ToastUtils.LENGTH_SHORT).show();
                        return;
                    }
                    Map<String, Object> map = new HashMap<>();

                    map.put("facardcode", jsonObject3.get("facardcode") == null ? "" : jsonObject3.get("facardcode").toString());
                    map.put("maname", jsonObject3.get("maname") == null ? "" : jsonObject3.get("maname").toString());
                    map.put("manumber", jsonObject3.get("manumber") == null ? "" : jsonObject3.get("manumber").toString());
                    map.put("facardid", jsonObject3.get("facardid") == null ? "" : jsonObject3.get("facardid").toString());
                    map.put("num", jsonObject3.optString("num") == null ? 0 : jsonObject3.optString("num"));
                    if (assetIdList.indexOf(map.get("facardcode")) == -1) {
                        dataMap.add(map);
                    }
                    assetIdList.add(jsonObject3.optString("facardcode"));

                    //通知ListView更改数据源
                    updateAssetList();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error", response.optString("message"));
                ToastUtils.makeText(IndexActivity.this, msg, ToastUtils.LENGTH_SHORT).show();
            }
        });
    }

    private void updateAssetList() {
        //通知ListView更改数据源
        if (listViewAdapter != null) {
            listViewAdapter.notifyDataSetChanged();
        } else {
            listViewAdapter = new ListViewAdapter(IndexActivity.this, dataMap, IndexActivity.this);
            lvAssets.setAdapter(listViewAdapter);
        }
        lvAssets.setSelection(dataMap.size() - 1);//设置显示列表的最后一项
    }

    /**
     * 通过人员id，查询人员信息
     *
     * @param jsonObject
     * @return void
     * @author: zhongfan
     * @Date 2022/2/15 17:47
     **/
    public void queryPersonnelInformation(JSONObject jsonObject) {
        service.post(jsonObject, HttpUrlComstants.QUERY_PERSONNEL_DETAILS, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                JSONArray data = response.optJSONArray("data");
                JSONObject jsonObject3 = null;

                try {
                    JSONObject jsonObject2 =data.getJSONObject(0);
                    JSONArray facardinfo = jsonObject2.optJSONArray("psninfo");
                    jsonObject3 =facardinfo.optJSONObject(0);

                    if (jsonObject3 == null) {
                        Toast.makeText(IndexActivity.this, "获取人员信息为空", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    //位置名称
                    assetsMap.put("field_6887600017549299712", jsonObject3.get("location") == null ? "" : jsonObject3.get("location").toString());
                    //使用人代码
                    assetsMap.put("field_6887600017557688327", jsonObject3.get("psncode") == null ? "" : jsonObject3.get("psncode").toString());
                    //使用人名称
                    assetsMap.put("field_6887600017557688328", jsonObject3.get("psnname") == null ? "" : jsonObject3.get("psnname").toString());

                    //查询下拉菜单值
//                    if (jsonObject3.get("location") != null && jsonObject3.get("centername") != null) {
//                        querySpinner(jsonObject3.get("location").toString(), jsonObject3.get("centername").toString());
//                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error", response.optString("message"));
                ToastUtils.makeText(IndexActivity.this, msg, ToastUtils.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 查询 位置编号、成本中心 下拉数据
     *
     * @param position
     * @param cost
     * @return void
     * @author: zhongfan
     * @Date 2022/2/15 21:00
     **/
    private void querySpinner(String position, String cost) {

        locationArray = new ArrayList<>();
        costArray = new ArrayList<>();

        /*查询位置信息*/
        service.post(new JSONObject(), HttpUrlComstants.QUERY_LOCATION_INFORMATION, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {

                try {
                    JSONArray centerinfo = JsonUtil.getJsonObjectArray(response, "locationinfo", IndexActivity.this);
                    for (int i = 0; i < centerinfo.length(); i++) {
                        if (centerinfo.get(i) == null) {
                            continue;
                        }
                        JSONObject jsonObject = new JSONObject(centerinfo.get(i).toString());
                        if (jsonObject.get("location") == null) {
                            continue;
                        }
                        locationArray.add(jsonObject.get("location") + BusinessConstants.SEPARATOR + jsonObject.get("locationname"));
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //initSpinner(locationArray, spLocationNumber, position, null);
                setATVData(locationArray,atvLocationNumber);
            }
        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error", response.optString("message"));
                ToastUtils.makeText(IndexActivity.this, msg, ToastUtils.LENGTH_SHORT).show();
            }
        });

        /*查询成本中心*/
        service.post(new JSONObject(), HttpUrlComstants.QUERY_COST_CENTER, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                try {
                    JSONArray centerinfo = JsonUtil.getJsonObjectArray(response, "centerinfo", IndexActivity.this);
                    for (int i = 0; i < centerinfo.length(); i++) {
                        if (centerinfo.get(i) == null) {
                            continue;
                        }
                        JSONObject jsonObject = new JSONObject(centerinfo.get(i).toString());
                        if (jsonObject.get("centername") == null) {
                            continue;
                        }
                        costArray.add(jsonObject.get("centercode") + BusinessConstants.SEPARATOR + jsonObject.get("centername"));
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //initSpinner(costArray, spCostCenter, cost, "field_6887600017549299712");
                //setATVData(costArray,atvCostCenter);
            }
        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error", response.optString("message"));
                ToastUtils.makeText(IndexActivity.this, msg, ToastUtils.LENGTH_SHORT).show();
            }
        });
    }


    /**
     * 给下拉框赋值
     *
     * @param starArray            数据集合
     * @param spinner              下拉框
     * @param specifyDefaultValues 默认选中值
     * @return void
     * @author: zhongfan
     * @Date 2022/2/16 14:34
     **/
    private void initSpinner(List<String> starArray, Spinner spinner, String specifyDefaultValues, String key) {
        starArray.add(0, BusinessConstants.PLEASE_SELECT);
        //声明一个下拉列表的数组适配器
        ArrayAdapter<String> starAdapter = new ArrayAdapter<>(IndexActivity.this, R.layout.item_select, starArray);

        //设置数组适配器的布局样式
        starAdapter.setDropDownViewResource(R.layout.item_dropdown);

        //设置下拉框的标题，不设置就没有难看的标题了
        spinner.setPrompt("请选择行星");
        //设置下拉框的数组适配器
        spinner.setAdapter(starAdapter);
        //设置下拉框默认的显示第一项
        if (StringUtils.isNotEmpty(specifyDefaultValues) && starArray.indexOf(specifyDefaultValues) != -1) {
            spinner.setSelection(starArray.indexOf(specifyDefaultValues));
        } else {
            spinner.setSelection(0);
        }
        starArray.indexOf(specifyDefaultValues);
        spinner.setSelection(0);
        //给下拉框设置选择监听器，一旦用户选中某一项，就触发监听器的onItemSelected方法
//        spinner.setOnItemSelectedListener(new IndexActivity.MySelectedListener(starArray,key));
        Log.v("starArry", starArray.toString());
    }

    /**
     * 下拉框选择事件
     *
     * @author: zhongfan
     * @Date 2022/2/16 14:34
     **/
    class MySelectedListener implements AdapterView.OnItemSelectedListener {
        List<String> starArray;
        String key;

        public MySelectedListener(List<String> starArray, String key) {
            this.starArray = starArray;
            this.key = key;
        }

        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            //位置代码
            assetsMap.put(key, starArray.get(i));
            //Toast.makeText(IndexActivity.this, "您选择的是：" + "starArray[i]", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    }

    @Override
    public void deletePosition(int saveposition) {
        Log.v("saveposition:", String.valueOf(saveposition));
        dataMap.remove(saveposition);
        assetIdList.remove(saveposition);
        listViewAdapter.setData(dataMap);
        listViewAdapter.notifyDataSetInvalidated();
    }

    private void initDateTime() {
        Calendar calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH) + 1;
        day = calendar.get(Calendar.DAY_OF_MONTH);
        hour = calendar.get(Calendar.HOUR);
        minute = calendar.get(Calendar.MINUTE);
    }

    @Override
    public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        this.year = year;
        this.month = monthOfYear+1 ;
        this.day = dayOfMonth;
    }

    /**
     * 时间改变的监听事件
     *
     * @param view
     * @param hourOfDay
     * @param minute
     */
    @Override
    public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
        this.hour = hourOfDay;
        this.minute = minute;
    }

    private ProgressDialog progressDialog;

    /**
     * 提示加载
     */
    public void showProgressDialog(String title, String message) {
        if (progressDialog == null) {

            progressDialog = ProgressDialog.show(IndexActivity.this, title, message, true, false);
        } else if (progressDialog.isShowing()) {
            progressDialog.setTitle(title);
            progressDialog.setMessage(message);
        }

        progressDialog.show();

    }

    /**
     * 隐藏提示加载
     */
    public void hideProgressDialog() {

        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.go_back:
                Intent intent = new Intent(IndexActivity.this, HomeActivity.class);
                IndexActivity.this.startActivity(intent);
                break;
            case R.id.tv_date:
                AlertDialog.Builder builder = new AlertDialog.Builder(IndexActivity.this);
                builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (date.length() > 0) { //清除上次记录的日期
                            date.delete(0, date.length());
                        }
                        tvDate.setText(date.append(String.valueOf(year)).append("-").append(String.valueOf(month)).append("-").append(day).append(""));
                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setNeutralButton("清空", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        tvDate.setText("");
                        dialog.dismiss();
                    }
                });
                final AlertDialog dialog = builder.create();
                View dialogView = View.inflate(IndexActivity.this, R.layout.dialog_date, null);
                final DatePicker datePicker = (DatePicker) dialogView.findViewById(R.id.datePicker);

                dialog.setTitle("设置日期");
                dialog.setView(dialogView);
                dialog.show();
                //初始化日期监听事件
                datePicker.init(year, month-1 , day, this);
                break;
            /*case R.id.et_borrower:
                if (BusinessConstants.SCAN_WHEN_SELECTED.equals(etBorrower.getText().toString())) {
                    etBorrower.setText("");
                }

                etBorrower.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                    @Override
                    public void onFocusChange(View v, boolean hasFocus) {
                        if (hasFocus) {
                            receiverFocusEvent = 1;
                        } else {
                            if (etBorrower.getText() == null || BusinessConstants.SCAN_WHEN_SELECTED.equals(etBorrower.getText().toString())) {
                                etBorrower.setText(BusinessConstants.SCAN_WHEN_SELECTED);
                            }
                            receiverFocusEvent = 0;
                        }
                    }
                });
                break;*/
            /*case R.id.et_project:
                if (BusinessConstants.PROJECT.equals(etProject.getText().toString())) {
                    etProject.setText("");
                }

                etProject.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                    @Override
                    public void onFocusChange(View v, boolean hasFocus) {
                        if (hasFocus) {
                            receiverFocusEvent = 1;
                        } else {
                            if (etProject.getText() == null || BusinessConstants.PROJECT.equals(etProject.getText().toString())) {
                                etProject.setText(BusinessConstants.PROJECT);
                            }
                            receiverFocusEvent = 0;
                        }
                    }
                });
                break;
            case R.id.et_purpose:
                if (BusinessConstants.PURPOSE.equals(etPurpose.getText().toString())) {
                    etPurpose.setText("");
                }

                etPurpose.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                    @Override
                    public void onFocusChange(View v, boolean hasFocus) {
                        if (hasFocus) {
                            receiverFocusEvent = 1;
                        } else {
                            if (etPurpose.getText() == null || BusinessConstants.PURPOSE.equals(etPurpose.getText().toString())) {
                                etPurpose.setText(BusinessConstants.PURPOSE);
                            }
                            receiverFocusEvent = 0;
                        }
                    }
                });
                break;*/
        }
    }
}
